package com.example.pengsiyuan.ppbluetoothle;

import android.database.sqlite.SQLiteDatabase;

import com.example.pengsiyuan.ppbluetoothle.dao.DeviceModelDao;
import com.example.pengsiyuan.ppbluetoothle.model.DeviceModel;
import com.peng.ppscalelibrary.BleManager.Model.BleDeviceModel;

import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private static DBManager dbManager;
    private DeviceModelDao deviceModelDao;
    private SQLiteDatabase sqLiteDatabase;
    public static  DBManager manager(){
        if (dbManager == null){
            synchronized (DBManager.class){
                if (dbManager == null){
                    dbManager = new DBManager();
                }
            }
        }
        return dbManager;
    }

    public DBManager() {
        deviceModelDao = PPApplication.getmDaoSession().getDeviceModelDao();
        sqLiteDatabase = PPApplication.getSqLiteDatabase();
    }

    public void insertDevice(BleDeviceModel model){
        DeviceModel deviceModel = new DeviceModel(model.getDeviceMac(), model.getDeviceName());
        deviceModelDao.insertOrReplace(deviceModel);
    }

    public void deleteDevice(BleDeviceModel model){
        try {
            sqLiteDatabase.delete(DeviceModelDao.TABLENAME,DeviceModelDao.Properties.DeviceMac.columnName+"=?",new String[]{model.getDeviceMac()});
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<BleDeviceModel>getDeviceList(){
        List<BleDeviceModel> deviceList = new ArrayList<BleDeviceModel>();
        List<DeviceModel>deviceModelList = deviceModelDao.loadAll();
        for (DeviceModel model: deviceModelList
             ) {
            BleDeviceModel deviceModel = new BleDeviceModel(model.getDeviceMac(), model.getDeviceName());
            deviceList.add(deviceModel);
        }
        return deviceList;
    }


}
